
var objSettings;
var tblNameDeepCompare;
var bTableCompareIsValid =false;
var bShowError =false;

function dba() {return $('#srva').val()+'.'+$('#dba').val();}
function dbb() {return $('#srvb').val()+'.'+$('#dbb').val();}

function syncTable(db1, db2, scTable, action) {
	if (action=="") {
		msgDialog("Please select `action` first", 'alert-info');	
	} else {
		url = 'ajax.php?get=tablesync&dbfrom='+db1+'&dbto='+db2+'&table='+scTable+'&action='+action;
msgDialog(url, 'alert-info');
		$.getJSON(url, function(data){
			if ((data['sync']['result']==false)||(String(data['sync']['message'])!="")) {
				msg = (String(data['sync']['message'])=="") ? url : data['sync']['message'];
				msgDialog('<strong>Sync Error </strong> '+msg, 'alert-danger');
			} else {
				msgDialog('<strong>Sync action succesfull on ('+scTable+').</strong>', 'alert-success');
				reCompare(scTable);
			}
		});
	}
}

function showHideTableTr(tr) {
	if (arguments.length==1) {
		// Direct hide when single row is added
		if ($('#chkHideSame').is(':checked') && tr.hasClass('same')) tr.hide();
		if ($('#chkHideSys').is(':checked') && tr.hasClass('system')) tr.hide();
	} else {
		// Check complete table to hide or not to hide, that is the question...
		$('#resTable tbody tr').show();
		if ($('#chkHideSame').is(':checked')) $('#resTable tbody tr.same').hide();
		if ($('#chkHideSys').is(':checked')) $('#resTable tbody tr.system').hide();
	}
}
function dorowcompare(relid) {
	rowSel = encodeURIComponent(relid);
	url = "ajax.php?get=rowcompare&dba="+dba()+"&dbb="+dbb()+"&table="+tblNameDeepCompare+"&rowsel="+rowSel;
msgDialog(url, "alert-info");
	$.getJSON(url, function(data){
		data = data["rowcompare"];
		$("#rowresult").html(data["html"]);
		showError(data['error']);
		$("#myCarousel").carousel(2);
	});
	return false;
}

function arrayResultToId(data) {
	for (index in data) {
		$('#'+String(index)).html(data[index]);
	}	
}

function deepCompareDB(dbtable, keys) {
	tblNameDeepCompare = dbtable;
	url = 'ajax.php?get=deepcompare&dba='+dba()+'&dbb='+dbb()+'&table='+dbtable;
msgDialog(url, 'alert-info');
	if (String(keys) != "") url += '&keys='+keys;
	$.getJSON(url, function(data){
		data = data['deepcompare'];
		arrayResultToId(data['html']);
		showError(data['error']);
		$('#myCarousel').carousel(1);
	});
}

function btnAlternativeKeys(dbtable) {
	keys = "";
	$('#frmKeys input:checked').each(function(i){keys += $(this).val()});
	deepCompareDB(dbtable, keys);
}

function msgDialog(msgTxt, msgType) {
	if (bShowError==false) {
	$('#topmessage .alert').attr('class', 'alert hide '+msgType);
	$('#topmessage .alert p').html(msgTxt);
		if (msgType=='alert-danger') {
			bShowError = true;
			$("#topmessage .alert").undelegate();
			$('#topmessage .alert').show().delay(9000).queue(function(){
				bShowError = false;
			});
		} else {
			$('#topmessage .alert').show().delay(9000).fadeOut(400).queue(function(){
				bShowError = false;
			});
		}
	}
}

function showError(s) {
	if (String(s)!="") {
		msgDialog('<strong>Compare Error </strong> '+s, 'alert-danger');
	}
}

function loadSettings(setfile) {
	$.getJSON('settings/open/'+setfile, function(data){
		objSettings = data['compare']; // Hier houden we ALLE settings in het geheugen!
		// ...
		$('#srva').val(objSettings['dba']['server']);
		$('#srvb').val(objSettings['dbb']['server']);
		$('#dba').val(objSettings['dba']['database']);
		$('#dbb').val(objSettings['dbb']['database']);
		$('#prefixa').val(objSettings['dbb']['prefix']);
		$('#prefixb').val(objSettings['dbb']['prefix']);
		// ...
		// ...
	});
}

function reCompare(cpTable) {
	url = 'ajax.php?get=comparedb&dba='+dba()+'&dbb='+dbb()+'&table='+cpTable;
	$.getJSON(url, function(data){
		data = data['compare'];
		showError(data['error']);
		$('#tr'+data['tablename']).replaceWith(data['html']);
		// Bind sync buttons
		$('a.synca2b').click(function() {
			syncTable(dba(), dbb(), $(this).attr('tbl'), $('#selact'+$(this).attr('relid')).val());
		});
		$('a.syncb2a').click(function() {
			syncTable(dbb(), dba(), $(this).attr('tbl'), $('#selact'+$(this).attr('relid')).val());
		});
	});
}

function compareDB(cpTable) {
	url = 'ajax.php?get=comparedb&dba='+dba()+'&dbb='+dbb()+'&table='+cpTable;
	msgDialog('<strong>Compare</strong> Now comparing tables:'+cpTable + ' ' + url, 'alert-info');
	$.getJSON(url, function(data){
		data = data['compare'];
		showError(data['error']);
		$('#resTable > tbody:last').append(data['html'])
		showHideTableTr($('#resTable > tbody tr:last'));
		$('#progress').width(data['progress']);
		if (data['curindex'] < data['count']) {
			// Get next
			compareDB(data['nexttable']);
		} else {
			// Bind sync buttons
			$('a.synca2b').click(function() {
				syncTable(dba(), dbb(), $(this).attr('tbl'), $('#selact'+$(this).attr('relid')).val());
			});
			$('a.syncb2a').click(function() {
				syncTable(dbb(), dba(), $(this).attr('tbl'), $('#selact'+$(this).attr('relid')).val());
				});
			$('#progress').delay(1000).hide("slow");
			msgDialog('<strong>Compare</strong> Database compare fully completed', 'alert-success');
		}
	});
}

// Make selected Server and Db hard in URL.
$('#dba,#dbb,#srva,#srva').change(function(event) {
	event.preventDefault();
	document.location.href='?dba='+dba()+'&dbb='+dbb();
});

// Compare button
$('#btncompare,#btnrecompare').click(function(event) {
	$('#myCarousel').carousel(0);
	event.preventDefault();
	if (($('#result').html()=="")||($(this).attr('id')=="btnrecompare")) {
		$('#progress').width(0);
		$('#progress').show();
		$('#result').html('<table id="resTable" class="table table-bordered table-striped"><thead><tr><th class="right">#</th><th>Table name</th><th>DB A</th><th class="center">Sync</th><th>DB B</th><th>Result</th><th width="100">Compare</th></tr></thead><tbody></tbody></table>');
		compareDB("");	
	}
});

// Database backup & drop
$('#btnbcka,#btndrpa,#btnbckb,#btndrpb').click(function(event) {
	event.preventDefault();
	name = String($(this).attr('id'));
	db = (String(name.substring(6,7))=="a") ? dba() : dbb() ;
	url = 'ajax.php?get=backup&db='+db+'&action='+name;	
	$.getJSON(url, function(data){
		msgDialog('<strong>Backup action succesfull.</strong> '+data['backup']['status'], 'alert-info');
	});
});

// Toon de database restore mogelijkheden in een lijst.
$('#btnresa,#btnresb').click(function(event) {
	event.preventDefault();
	name = String($(this).attr('id'));
	db = (String(name.substring(6,7))=="a") ? dba() : dbb() ;
	url = 'ajax.php?get=backup&db='+db+'&action=cmdlst';
msgDialog(url, 'alert-info');			
	$.getJSON(url, function(data){
		$('#myModal .modal-header h3').html('Database restore');
		msg = String(data['backup']['htmllist']);
		$('#myModal .modal-body').html('<p>Let op, database wordt overschreven met de restored database. MODx heeft veel in de cache staan, maak deze direct leeg nadat u een restore heeft uitgvoerd.</p>Maak hieronder uw keuze:<br/><ul>'+msg+'</ul>');
		$('#myModal').modal({keyboard: true});

		$('a.dbrestore').click(function(event) {
			event.preventDefault();
			url = 'ajax.php?get=backup&'+$(this).attr('href');
msgDialog(url, 'alert-info');			
			$('#myModal').modal('hide').on('hidden', function () {
				$.getJSON(url, function(data2){
					msgDialog("Restore result: "+data2['backup']['status'], 'alert-info');
				});	
			});	
		});
	});
});

$('#mnusettings').click(function(event) {
	event.preventDefault();
	$('#mySettings').modal('show');
});
	
$('#chkHideSame, #chkHideSys, #chkUsePrefix').change(function() {
	showHideTableTr();
});
	
$(document).ready(function() {

	// Laad de lijst `settings` bestanden
	$.getJSON('settings/list', function(data){
		for (var i = 0; i< data.length; i++) {
				$('#ulopenlist').append('<li><a class="opencompare" relid="'+data[i]+'" href="#">'+data[i]+'</a></li>');
		}
		// Laad de gekozen `settings` bestand indien gekozen in het menu.
		$('.opencompare').click(function(event) {
			event.preventDefault();
			loadSettings($(this).attr('relid'));
		});
	});

	$('#myCarousel').bind('slid', function() {
		// Initialize TAB's on deepresult, and show best guess.
		if ($('#myCarousel div.item.active').attr('id')=='deepresult') {
			// Row compare button
			$(".btnrowcompare").click(function(event) {
				event.preventDefault();
				dorowcompare($(this).attr("relid"));
			});
			// Activate TAB's
			$('#deepTabs a').click(function (e) {
				e.preventDefault();
				$(this).tab('show');
			})
			// Guess active TAB
			if (String($('#lbldefinition').html()).indexOf("identical")>0) {
				$('#lbldifferent').tab('show');
			} else {
				$('#deepTabs a:first').tab('show');
			}
		}
	});
	
	// Laad de UNDO lijst
	$('ul#ulundolist').menuUndo({open:true});
	
	msgDialog("Load succesfull", 'alert-success');

});
